// goods-item.js
var app = getApp();
var iFDU = require('../../utils/iFDU.js');
var WxParse = require('../../components/wxParse/wxParse.js');
Page({

  data: {
    config: app.config,
    globalData: app.globalData,

    goodsId: 0,
    goodsDetail: {},
    cartCount: 0,
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 500,
    fullServices: {
      0: {
        name: '专属定制',
        desc: '逸见服饰为您提供极简便捷的专属定制体验，让您轻松玩转死人定制！',
        icon: '../../images/common/custom.png'
      },
      1: {
        name: '免费绣字',
        desc: '我们免费为您提供个性化的袖口刺绣服务，让您的衬衫与众不同！',
        icon: '../../images/common/word.png'
      },
      2: {
        name: '身型保险计划',
        desc: '逸见服饰独家创新的极致售后保障！身材有变化？我们来赔付！',
        icon: '../../images/common/security.png'
      },
      3: {
        name: '红包抵现',
        desc: '衬衫不够合体？我们负责为您修改！您满意，我们更开心！',
        icon: '../../images/common/redbag.png'
      },
      24: {
        name: '极速定制',
        desc: '此商品支持极速定制，请查看页面说明',
        icon: '../../images/common/fast-icon.png'
      }
    },
    services: [],

    fullDetailServices: {
      24: {
        name: '极速定制',
        desc: '此商品支持极速定制，请查看页面说明',
        icon: '../../images/common/fast-icon.png'
      },
      3: {
        name: '红包抵现',
        desc: '该商品支持红包抵现，不要忘记使用哦！',
        icon: '../../images/common/redbag.png'
      },
      0: {
        name: '专属定制',
        desc: '逸见服饰为您提供极简便捷的专属定制体验，让您轻松玩转私人定制！',
        icon: '../../images/common/custom.png'
      },
      1: {
        name: '免费绣字',
        desc: '我们免费为您提供个性化的袖口刺绣服务，让您的衬衫与众不同！',
        icon: '../../images/common/word.png'
      },
      2: {
        name: '身型保险计划',
        desc: '逸见服饰独家创新的极致售后保障！身材有变化？我们来赔付！',
        icon: '../../images/common/security.png'
      },
      4: {
        name: '免费修改',
        desc: '衬衫不够合体？我们负责为您修改！您满意，我们更开心！',
        icon: '../../images/common/modify.png'
      }
    },
    detailServices: [],
    serviceStatus: false,
    skuModalStatus: false,
    skuItemWidth: 0,
    skuNum: 1,
    validSkuGroups: [],
    skuItemsStatus: {},
    selectedmarketingProductId: 0,
    selectedmarketingProductIds: [],
    marketingProductsId: 0,

    modalButtonStatus: 0,
    selectedSkuPrice: 0,
    countdown: 0,
    counter: {},
    emptyStatus: false,
    channelId: 0
  },

  showServiceDetail: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      serviceStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideServiceDetail: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        serviceStatus: false
      })
    }.bind(this), 200)
  },

  showSkuDetail: function () {
    this.reset();
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      skuModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideSkuDetail: function (cb) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        skuModalStatus: false
      })
      if (typeof cb == 'function') {
        cb();
      }
    }.bind(this), 200)
  },

  minus: function () {
    var that = this;
    var skuNum = this.data.skuNum ? (this.data.skuNum - 1) : 0;
    this.setData({
      skuNum: skuNum
    });
    that.determineModalButtonStatus();
  },
  plus: function () {
    var that = this;
    var skuNum = this.data.skuNum ? this.data.skuNum + 1 : 1;
    this.setData({
      skuNum: skuNum
    });
    that.determineModalButtonStatus();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      that.data.goodsId = scene;
    } else {
      that.data.goodsId = options.goodsId;
    }

    var firstShow = 0;
    if (options.firstShow) {
      firstShow = 1;
    }

    var channelId = options.channelId;
    if (channelId) {
      that.data.channelId = channelId;
    }

    var screenWidth = wx.getSystemInfoSync().screenWidth * 2;
    wx.showLoading({
      title: '加载中',
    });
    app.getUserInfo(function (globalData) {
      that.setData({
        globalData: globalData
      });

      var param = {
        userId: globalData.userId,
        mainProductId: that.data.goodsId,
      };
      if (channelId) {
        param['channelId'] = channelId;
      }
      iFDU.api.doGet(
        'product/getProductInfo', param,
        function (data) {
          var goodsDetail = data.productView;
          // 是否支持身型保险计划
          var supportBodyShapeInsur = goodsDetail.marketingProducts && goodsDetail.marketingProducts.length > 0;
          
          wx.setNavigationBarTitle({
            title: goodsDetail.title//页面标题为路由参数
          })
          WxParse.wxParse('article', 'html', goodsDetail.product_content, that, 5);

          var skuItemsStatus = {};
          if (goodsDetail.mainSkuViews && goodsDetail.mainSkuViews.length > 0) {
            for (var i = 0; i < goodsDetail.mainSkuViews.length; i++) {
              var property = goodsDetail.mainSkuViews[i];
              skuItemsStatus[property.id] = {};
              if (property.subSkus && property.subSkus.length > 0) {
                for (var j = 0; j < property.subSkus.length; j++) {
                  var status = {};
                  status['selected'] = 0;
                  status['blocked'] = 0;
                  skuItemsStatus[property.id][property.subSkus[j].id] = status;
                }
              }
            }
          }


          var validSkuGroups = [];
          // 是否支持红包抵现
          var supportRedbag = false;
          if (goodsDetail.subProductViews && goodsDetail.subProductViews.length > 0) {
            for (var i = 0; i < goodsDetail.subProductViews.length; i++) {
              if (goodsDetail.subProductViews[i].is_redbag == 1) {
                supportRedbag = true;
                break;
              }
            }
          }
          if (goodsDetail.subProductViews && goodsDetail.subProductViews.length > 0 && goodsDetail.subProductViews[0].subSkus) {
            for (var i = 0; i < goodsDetail.subProductViews.length; i++) {
              var validSkuGroup = [];
              for (var j = 0; j < goodsDetail.subProductViews[i].subSkus.length; j++) {
                validSkuGroup.push(goodsDetail.subProductViews[i].subSkus[j].main_sku_id + '-' + goodsDetail.subProductViews[i].subSkus[j].id);
              }
              validSkuGroups.push(validSkuGroup.join('|'));
            }
          }

          var services = [];
          if (goodsDetail.is_need_figure == 0) {
            services.push(that.data.fullServices['0']);
          }
          if (goodsDetail.is_broider == 1) {
            services.push(that.data.fullServices['1']);
          }
          if (supportBodyShapeInsur) {
            services.push(that.data.fullServices['2']);
          }
          for (let i = 0; i < goodsDetail.marketingProducts.length; i++) {
            if (goodsDetail.marketingProducts[i].id == 24) {
              services.push(that.data.fullServices['24']);
            }
          }
          if (services.length < 4) {
            if (supportRedbag) {
              services.push(that.data.fullServices['3']);
            }
          }

          var detailServices = [];
          for (let i = 0; i < goodsDetail.marketingProducts.length; i++) {
            if (goodsDetail.marketingProducts[i].id == 24) {
              detailServices.push(that.data.fullServices['24']);
            }
          }
          if (supportRedbag) {
            detailServices.push(that.data.fullDetailServices['3']);
          }
          if (goodsDetail.is_need_figure == 0) {
            detailServices.push(that.data.fullDetailServices['0']);
          }
          if (goodsDetail.is_broider == 1) {
            detailServices.push(that.data.fullDetailServices['1']);
          }
          if (supportBodyShapeInsur) {
            detailServices.push(that.data.fullDetailServices['2']);
          }
          if (goodsDetail.is_need_figure == 0) {
            detailServices.push(that.data.fullDetailServices['4']);
          }

          var countdownDesc = that.formatSeconds(goodsDetail.countdownSecond);

          var timer = setInterval(function() {
            if (that.data.countdown > 0) {
              that.setData({
                countdown: that.data.countdown - 1,
                countdownDesc: that.formatSeconds(that.data.countdown - 1),
              });
            } else {
              clearInterval(timer);
            }
          }, 1000);
          that.setData({
            skuItemWidth: (screenWidth - 30) / 4 - 34,
            goodsDetail: goodsDetail,
            skuItemsStatus: skuItemsStatus,
            validSkuGroups: validSkuGroups,
            services: services,
            detailServices: detailServices,
            countdown: goodsDetail.countdownSecond,
            countdownDesc: countdownDesc,
            counter: timer,
            emptyStatus: false
          });

          if (firstShow) {
            that.goBuy();
          }
          wx.hideLoading();
        }, function(data) {
          that.setData({
            emptyStatus: true
          });
          wx.hideLoading();
        }
      );
    });
  },

  onShow: function () {
    var that = this;

    that.loadCartCount();
  },

  formatSeconds: function (value) {
    var theTime = parseInt(value);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    if(theTime > 60) {
      theTime1 = parseInt(theTime / 60);
      theTime = parseInt(theTime % 60);
      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60);
        theTime1 = parseInt(theTime1 % 60);
      }
    }
        var result = "" + parseInt(theTime) + "秒";
    if(theTime1 > 0) {
      result = "" + parseInt(theTime1) + "分" + result;
    }
        if(theTime2 > 0) {
      result = "" + parseInt(theTime2) + "小时" + result;
    }
    return result;
  },

  loadCartCount: function () {
    var that = this;
    iFDU.api.doGet(
      'cart/getItemCount',
      {
        userId: that.data.globalData.userId,
        rnd: Math.random()
      },
      function (data) {
        that.setData({
          cartCount: data.itemCount
        });
      }
    );
  },

  reset: function () {
    var that = this;
    var skuItemsStatus = that.data.skuItemsStatus;
    if (skuItemsStatus) {
      for (var mainKey in skuItemsStatus) {
        for (var subKey in skuItemsStatus[mainKey]) {
          skuItemsStatus[mainKey][subKey] = {
            selected: 0,
            blocked: 0
          }
        }
      }
    }
    that.setData({
      skuNum: 1,
      skuItemsStatus: skuItemsStatus,
      selectedmarketingProductId: 0,
      selectedSkuPrice: 0,
    });

    that.determineModalButtonStatus();
  },

  selectMarketingProduct: function (e, id) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var current = that.data.selectedmarketingProductId;
    var marketingProductsId = e.currentTarget.dataset.marketingProductsId;
    var setArrIndex = 'selectedmarketingProductIds[' + marketingProductsId + ']'
    // 取消选择
    if (id == current) {
      that.setData({
        selectedmarketingProductId: 0,
        [setArrIndex]: 0
      });
    } else {
      that.setData({
        selectedmarketingProductId: id,
        [setArrIndex]: id
      });
    }
  },

  selectSku: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.pid;
    var id = e.currentTarget.dataset.id;
    var skuItemsStatus = that.data.skuItemsStatus;
    if (skuItemsStatus[pid][id]['blocked'] == 1) {
      return;
    }
    if (skuItemsStatus[pid][id]['selected'] == 1) {
      skuItemsStatus[pid][id]['selected'] = 0;
    } else {
      for (var subKey in skuItemsStatus[pid]) {
        skuItemsStatus[pid][subKey]['selected'] = 0;
      }
      skuItemsStatus[pid][id]['selected'] = 1;
    }

    // 已选Sku
    var selectedSkuIds = that.calcSeletedSkuIds();
    // 可选Sku
    var validSkuIds = that.filterAttrs(selectedSkuIds);
    // 已选属性
    var selectMainKeys = {};
    for (var index in selectedSkuIds) {
      selectMainKeys[selectedSkuIds[index].split('-')[0]] = 1;
    }

    // 未选属性
    var unselectMainKeys = {};
    for (var mainKey in skuItemsStatus) {
      if (selectMainKeys[mainKey] && selectMainKeys[mainKey] == 1) {
      } else {
        unselectMainKeys[mainKey] = 1;
      }
    }

    // 设置未选择属性中的不可选Sku
    for (var mainKey in skuItemsStatus) {
      for (var subKey in skuItemsStatus[mainKey]) {
        if (unselectMainKeys[mainKey] && unselectMainKeys[mainKey] == 1) {
          var contain = false;
          for (var index in validSkuIds) {
            if (mainKey + '-' + subKey == validSkuIds[index]) {
              contain = true;
              break;
            }
          }
          if (contain) {
            skuItemsStatus[mainKey][subKey]['blocked'] = 0;
          } else {
            skuItemsStatus[mainKey][subKey]['blocked'] = 1;
          }
        }
      }
    }

    // 设置已选属性的同级Sku是否可选
    for (var mainKey in selectMainKeys) {
      var selectedSubKey = '';
      for (var subKey in skuItemsStatus[mainKey]) {
        if (skuItemsStatus[mainKey][subKey]['selected'] == 1) {
          selectedSubKey = subKey;
          break;
        }
      }

      // 除了当前属性，其他属性选择的Sku
      var otherSelectedSkuIds = that.del_array_val(selectedSkuIds, mainKey + '-' + selectedSubKey);
      var otherValidSkuIds = that.filterAttrs(selectedSkuIds);

      for (var subKey in skuItemsStatus[mainKey]) {
        if (subKey != selectedSubKey) {
          if (otherSelectedSkuIds.length > 0) {
            var contain = false;
            for (var index in otherValidSkuIds) {
              if (mainKey + '-' + subKey == otherValidSkuIds[index]) {
                contain = true;
                break;
              }
            }
            if (contain) {
              skuItemsStatus[mainKey][subKey]['blocked'] = 0;
            } else {
              skuItemsStatus[mainKey][subKey]['blocked'] = 1;
            }
          } else {
            skuItemsStatus[mainKey][subKey]['blocked'] = 0;
          }
        }
      }
    }

    that.setData({
      skuItemsStatus: skuItemsStatus
    });

    that.determineModalButtonStatus();
  },

  calcSeletedSkuIds: function () {
    var that = this;
    var list = [];
    var skuItemsStatus = that.data.skuItemsStatus;
    for (var mainKey in skuItemsStatus) {
      for (var subKey in skuItemsStatus[mainKey]) {
        if (skuItemsStatus[mainKey][subKey]['selected'] == 1) {
          list.push(mainKey + '-' + subKey);
        }
      }
    }
    return list;
  },

  /**
   * 获取所有包含指定节点的路线
   */
  filterProduct: function (ids) {
    var that = this;
    var validSkuGroups = that.data.validSkuGroups;
    var result = [];
    for (var i = 0; i < validSkuGroups.length; i++) {
      var validSku = '|' + validSkuGroups[i] + '|';
      var contain = true;
      for (var index in ids) {
        if (validSku.indexOf('|' + ids[index] + '|') < 0) {
          contain = false;
          break;
        }
      }
      if (contain) {
        result.push(validSkuGroups[i]);
      }
    }
    return result;
  },

  /**
   * 获取 经过已选节点 所有线路上的全部节点
	 * 根据已经选择的属性值，得到余下还能选择的属性值
   */
  filterAttrs: function (ids) {
    var that = this;
    var products = that.filterProduct(ids);
    var result = [];

    for (var i = 0; i < products.length; i++) {
      result = result.concat(products[i].split('|'));
    }
    return result;
  },

  del_array_val: function (arr, val) {
    var a = [];
    for (var k in arr) {
      if (arr[k] != val) {
        a.push(arr[k]);
      }
    }
    return a;
  },

  determineModalButtonStatus: function () {
    var that = this;
    var enable = true;
    var hasSku = that.data.goodsDetail.mainSkuViews && that.data.goodsDetail.mainSkuViews.length > 0;
    if (that.data.skuNum < 1) {
      enable = false;
    }

    var selectSkus = [];
    if (hasSku) {
      var skuItemsStatus = that.data.skuItemsStatus;
      var selectedAll = true;
      for (var mainKey in skuItemsStatus) {
        var hasSelected = false;
        for (var subKey in skuItemsStatus[mainKey]) {
          if (skuItemsStatus[mainKey][subKey]['selected'] == 1) {
            hasSelected = true;
            selectSkus.push(subKey);
            break;
          }
        }
        if (!hasSelected) {
          selectedAll = false;
          break;
        }
      }
      if (!selectedAll) {
        enable = false;
      }
    }

    if (enable) {
      var selectedSkuPrice = 0;
      if (hasSku) {
        var subProductViews = that.data.goodsDetail.subProductViews;
        var validSkuMap = {};
        for (var i in subProductViews) {
          var tempKey = [];
          for (var j in subProductViews[i]['subSkus']) {
            tempKey.push(subProductViews[i]['subSkus'][j].id);
          }
          validSkuMap[tempKey.join('|')] = {
            id: subProductViews[i]['id'],
            logo: subProductViews[i]['logo'],
            price: subProductViews[i]['channelPrice']
          };
        }
        selectedSkuPrice = validSkuMap[selectSkus.reverse().join('|')].price;
      }


      if (that.data.modalButtonStatus == 22) {
        that.setData({
          modalButtonStatus: 21,
          selectedSkuPrice: selectedSkuPrice
        });
      } else if (that.data.modalButtonStatus == 12) {
        that.setData({
          modalButtonStatus: 11,
          selectedSkuPrice: selectedSkuPrice
        });
      } else {
        that.setData({
          selectedSkuPrice: selectedSkuPrice
        });
      }
    } else {
      if (that.data.modalButtonStatus == 21) {
        that.setData({
          modalButtonStatus: 22,
          selectedSkuPrice: 0,
        });
      } else if (that.data.modalButtonStatus == 11) {
        that.setData({
          modalButtonStatus: 12,
          selectedSkuPrice: 0,
        });
      }
    }
  },

  goHome: function (e) {
    wx.switchTab({
      url: '../home/home',
    })
  },

  goCart: function (e) {
    wx.switchTab({
      url: '../goods-cart/goods-cart',
    })
  },

  goBuy: function (e) {
    var that = this;
    that.setData({
      modalButtonStatus: 12
    });
    that.showSkuDetail();
  },

  goAdd: function (e) {
    var that = this;
    that.setData({
      modalButtonStatus: 22
    });
    that.showSkuDetail();
  },

  addCart: function (e) {
    var that = this;
    var data = {
      userId: that.data.globalData.userId,
      mainProductId: that.data.goodsId,
      count: that.data.skuNum
    };
    var hasSku = that.data.goodsDetail.mainSkuViews && that.data.goodsDetail.mainSkuViews.length > 0;
    if (hasSku) {
      var selectedSkuIds = that.calcSeletedSkuIds();
      var selectedSubSkuIds = [];
      for (var i in selectedSkuIds) {
        selectedSubSkuIds.push(selectedSkuIds[i].split('-')[1]);
      }
      data['subSkuIds'] = selectedSubSkuIds.join(',');
    }
    if (that.data.selectedmarketingProductIds && that.data.selectedmarketingProductIds.length > 0) {
      var addCartArr = []
      for (let i = 0; i < that.data.selectedmarketingProductIds.length; i++) {
        if (that.data.selectedmarketingProductIds[i] != 0 && that.data.selectedmarketingProductIds[i]) {
          addCartArr.push(that.data.selectedmarketingProductIds[i])
        }
      }
      data['subMarketingProductIds'] = addCartArr.join(',')
    }

    iFDU.api.doGet('cart/addCart', data, function (data) {
      that.loadCartCount();
      that.hideSkuDetail(function () {
        iFDU.toast.showToast({
          title: '加入购物车成功',
          mask: false
        })
      });
    });
  },

  buy: function (e) {
    var that = this;
    var goods = {
      goods_id: that.data.goodsId,
      goods_count: that.data.skuNum,
      goods_logo: that.data.goodsDetail.big_logo,
      goods_main_id: that.data.goodsDetail.id,
      goods_title: that.data.goodsDetail.title,
      is_need_figure: that.data.goodsDetail['is_need_figure'],
      is_broider: that.data.goodsDetail['is_broider'],
      is_virtual: that.data.goodsDetail['is_virtual'],
      goods_price: that.data.goodsDetail.first_sku_price,
      sleeve_word: '',
      sleeve_word_type: 1,
      marketing_goods_propertie_ids: []
    };
    var marketingGoodsNames = [];
    var marketingNames = [];
    var marketingGoodsProperties = [];
    for (var marketIndex = 0; marketIndex < that.data.selectedmarketingProductIds.length; marketIndex++) {
      if (that.data.selectedmarketingProductIds[marketIndex] != 0 && that.data.selectedmarketingProductIds[marketIndex] != undefined) {
        // goods['marketing_goods_propertie_ids'] = [];
        goods['marketing_goods_propertie_ids'].push(that.data.selectedmarketingProductIds[marketIndex])
        var bodyInsur = [];
        for (var index in that.data.goodsDetail.marketingProducts[marketIndex].subMarketingProducts) {
          if (that.data.selectedmarketingProductIds[marketIndex] == that.data.goodsDetail.marketingProducts[marketIndex].subMarketingProducts[index].id) {
            bodyInsur[marketIndex] = that.data.goodsDetail.marketingProducts[marketIndex].subMarketingProducts[index];
          }
        }
        marketingGoodsNames.push(bodyInsur[marketIndex].name + ' | ￥' + (bodyInsur[marketIndex].price / 100.00))
        marketingGoodsProperties.push({
          id: bodyInsur[marketIndex].id,
          name: bodyInsur[marketIndex].name,
          price: bodyInsur[marketIndex].price
        })
        marketingNames.push(that.data.goodsDetail.marketingProducts[marketIndex].name)
        goods['marketing_goods_properties'] = marketingGoodsProperties;
        goods['marketing_goods_propertie_names'] = marketingGoodsNames;
        goods['marketing_properties_names'] = marketingNames;
        // console.log('bodyInsur', bodyInsur)
      }
    }

    var hasSku = that.data.goodsDetail.mainSkuViews && that.data.goodsDetail.mainSkuViews.length > 0;
    if (hasSku) {
      var selectSkus = [];
      for (var index in that.data.goodsDetail.mainSkuViews) {
        var subSkus = that.data.skuItemsStatus[that.data.goodsDetail.mainSkuViews[index].id];
        var subSku = {};
        for (var subKey in subSkus) {
          if (subSkus[subKey]['selected'] == 1) {
            subSku['id'] = subKey;
            break;
          }
        }
        for (var j in that.data.goodsDetail.mainSkuViews[index]['subSkus']) {
          if (that.data.goodsDetail.mainSkuViews[index]['subSkus'][j].id == subSku['id']) {
            subSku['name'] = that.data.goodsDetail.mainSkuViews[index]['subSkus'][j].name;
            break;
          }
        }
        selectSkus.push(subSku);
      }
      goods['subSkus'] = selectSkus;

      var subProductViews = that.data.goodsDetail.subProductViews;
      var validSkuMap = {};
      for (var i in subProductViews) {
        var tempKey = [];
        for (var j in subProductViews[i]['subSkus']) {
          tempKey.push(subProductViews[i]['subSkus'][j].id);
        }
        validSkuMap[tempKey.join('|')] = {
          id: subProductViews[i]['id'],
          logo: subProductViews[i]['logo'],
          price: subProductViews[i]['channelPrice']
        };
      }

      var key = [];
      for (var i in selectSkus) {
        key.push(selectSkus[i].id);
      }

      goods['goods_id'] = validSkuMap[key.join('|')].id;
      goods['goods_logo'] = validSkuMap[key.join('|')].logo;
      goods['goods_price'] = validSkuMap[key.join('|')].price;
    } else {
      var subProductViews = that.data.goodsDetail.subProductViews;
      if (subProductViews && subProductViews.length > 0) {
        goods['goods_id'] = subProductViews[0].id;
        goods['goods_logo'] = subProductViews[0].logo;
        goods['goods_price'] = subProductViews[0].channelPrice;
      }
    }

    var goodsList = [goods];
    console.log('goodsList', goodsList);
    wx.setStorageSync('goodsList', JSON.stringify(goodsList));
    that.hideSkuDetail(function () {
      wx.navigateTo({
        url: '../order-confirm/order-confirm?fromCart=false&virtual=0&channelId=' + that.data.channelId,
      })
    });
  },

  showGift: function (e) {
    iFDU.toast.showToast({
      title: '送礼功能稍后开通，敬请期待！',
      mask: false
    });
  },

  showProtocol: function (e) {
    wx.navigateTo({
      url: '../body-shape-insur/body-shape-insur',
    })
  },

  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: that.goodsDetail.title,
      path: 'pages/goods-item/goods-item?goodsId=' + that.goodsId,
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  }
})